package home.my.base.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
	private static final String defaultPattern = "yyyy-MM-dd";
	private static final String defaultFullPattern = "yyyy-MM-dd HH:mm:ss";

	public DateUtil() {
	}

	private static String formatDateToStr(Date instance, String pattern){
		if(instance==null){
			return null;
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		return dateFormat.format(instance);
	}

	private static String formatDateToStr(Long instance, String pattern){
		if(instance==null){
			return null;
		}
		Date date = new Date(instance);
		return formatDateToStr(date,pattern);
	}

	public static String formatDateTimeToStr(Date instance){
		return formatDateToStr(instance,defaultFullPattern);
	}
	
	public static String formatDateTimeToStr(Long instance){
		return formatDateToStr(instance,defaultFullPattern);
	}
	
	public static String formatDateToStr(Date instance){
		if(instance==null){
			return null;
		}
		return formatDateToStr(instance,defaultPattern);
	}

	public static Date parseStrToDate(String instance, String pattern){
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		try {
			return dateFormat.parse(instance);
		} catch (ParseException e) {
			return null;
		}
	}

	public static Date parseStrToDate(String instance){
		return parseStrToDate(instance,defaultPattern);
	}
	
	/**
	 * 把日期后的时间归0 变成(yyyy-MM-dd 00:00:00:000)
	 * 
	 * @param date
	 * @return Date
	 */
	public static final Date zerolizedTime(Date fullDate) {
		if(fullDate==null){
			return null;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(fullDate);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime();
	}

	/**
	 * 把日期后的时间归0 变成(yyyy-MM-dd 23:59:59:999)
	 * 
	 * @param date
	 * @return Date
	 */
	public static final Date maxlizedTime(Date fullDate) {
		if(fullDate==null){
			return null;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(fullDate);
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		cal.set(Calendar.MILLISECOND, 999);
		return cal.getTime();
	}
	
	/**
	 * 加减天数
	 * 
	 * @param date
	 * @return Date
	 */
	public static final Date increaseDate(Date aDate, int days) {
		if(aDate==null){
			return null;
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(aDate);
		cal.add(Calendar.DAY_OF_MONTH, days);
		return cal.getTime();
	}


}
